﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Production;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.Production
{
    /// <summary>
    /// 产线管理信息录入处理类
    /// </summary>
    public class CreateProductionHnadler : IRequestHandler<CreateProductionCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProductionModel> produRepo;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateProductionHnadler(IBaseRespository<ProductionModel> produRepo,
            IMapper mapper,ICodeRuleService codeRuleService)
        {
            this.produRepo = produRepo;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateProductionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var model=mapper.Map<ProductionModel>(request);
            model.CreateName=request.CreateName;

            //编码
            if (string.IsNullOrEmpty(model.Productioncode))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.FactoryModeling.ProductionModel");
                if (!string.IsNullOrEmpty(code))
                {
                    model.Productioncode = code;
                }
                else
                {
                    model.Productioncode = $"CX{DateTime.Now:yyyyMMddHHmmss}";
                }
            }


            var r=await produRepo.AddAsync(model);
            if (r>0)
            {
                res.Data=r;
                res.Code = ApiEnum.Success;
                res.Msg = "产线管理信息录入成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "产线管理信息录入失败";
            }
            return res;
        }
    }
}
